<template>
  <el-form ref="formData" :model="formData" label-width="80px" :rules="rules">
    <el-form-item :hidden="$route.query.id" label="所属学科" prop="subjectID">
      <el-select v-model="formData.subjectID" placeholder="请选择" style="width: 100%;">
        <el-option
          v-for="item in subjectList"
          :key="item.id"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="标签名称" prop="tagName">
      <el-input v-model="formData.tagName" placeholder="请输入标签名称" />
    </el-form-item>
    <el-form-item class="btn">
      <el-button size="small" @click="$emit('close')">取消</el-button>
      <el-button size="small" type="primary" @click="onSubmit">确认</el-button>
    </el-form-item>
  </el-form>

</template>

<script>
import { subjectSimpleList, add, detail, update } from '@/api/hmmm/tags'
export default {
  name: 'TagsDialog',
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    tagId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      subjectList: [],
      formData: {
        subjectID: Number(this.$route.query.id) ? Number(this.$route.query.id) : null,
        tagName: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择所属学科', trigger: 'change' }],
        tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 获取学科简单列表方法
    this.getSubjectSimpleList()

    // 获取标签详情方法
    this.editTag()
  },
  methods: {
    // 获取学科简单列表
    async getSubjectSimpleList() {
      const res = await subjectSimpleList()
      this.subjectList = res.data
    },

    // 提交添加标签
    async addTagSubmit() {
      const res = await add(this.formData).catch(err => err)
      if (res.status === 200) {
        this.$message.success('添加标签成功')
      }
      this.$emit('update')
    },

    // 获取编辑标签详情
    async editTag() {
      if (this.isEdit === true) {
        const res = await detail(this.tagId)
        this.formData = res.data
      }
    },

    // 提交编辑标签数据
    async editTagSubmit() {
      const res = await update(this.formData)
      if (res.status === 200) {
        this.$message.success('编辑标签成功')
      }
      this.$emit('update')
    },

    // 提交添加或编辑表单数据
    onSubmit() {
      this.$refs.formData.validate(valid => {
        if (!valid) return
        this.isEdit ? this.editTagSubmit() : this.addTagSubmit()
      })
    }
  }
}
</script>

<style scoped lang='scss'>
  .btn {
    margin-left: 230px;
  }

</style>
